package client

import (
	"encoding/json"
	"github.com/pkg/errors"
	"gopkg.in/mgo.v2/bson"
	"jkgo/jk/jklog"
	"jkgo/jkdbs"
	"time"
)

type STClient struct {
	db *jkdbs.Mongo
}

type UploadDataInfo struct {
	CreateTime int64    `bson:"createTime"`
	UploadTime int64    `bson:"uploadTime"`
	Id         string   `bson:"id"`
	Cmd        string   `bson:"cmd"`
	Class      string   `bson:"class"`
	Label      []string `bson:"label"`
	Attr       string   `bson:"attr"`
}

func STClientNew(mongo *jkdbs.Mongo) (*STClient, error) {
	return &STClient{
		db: mongo,
	}, nil
}

func (st *STClient) SaveData(buf string) error {
	jklog.L().Debugln("recv buf ", buf)
	var up UploadDataInfo
	err := json.Unmarshal([]byte(buf), &up)
	if err != nil {
		return err
	}
	up.UploadTime = time.Now().Unix()
	if len(up.Cmd) == 0 {
		return errors.New("cmd is null")
	}
	jklog.L().Debugln("start to save to db")
	err = st.db.Cnew("proj", up.Cmd).Insert(up)
	return err
}

func (st *STClient) GetData(cmd, class string) (string, error) {
	jklog.L().Debugln("go to get data class = ", class)
	find := bson.M{
		"cmd": cmd,
	}
	if len(class) > 0 {
		find["class"] = class
	}
	var up UploadDataInfo
	err := st.db.Cnew("proj", cmd).Find(find).All(&up)
	if err != nil {
		return "", err
	}
	d, err := json.Marshal(up)
	return string(d), err
}
